<template>
    <div class="knowledge-documents-container">
        <a-page-header title="知识库文档管理" style="padding: 16px 0; background: #fff;" />

        <!-- 搜索与过滤区域 -->
        <a-card style="margin-bottom: 16px">
            <a-row :gutter="16">
                <a-col :span="6">
                    <a-input-search v-model:value="searchKeyword" placeholder="搜索文档名称..." style="width: 100%"
                        @search="handleSearch" allow-clear />
                </a-col>
                <a-col :span="4">
                    <a-select v-model:value="categoryFilter" placeholder="知识库类型" style="width: 100%"
                        @change="handleFilter" allow-clear>
                        <a-select-option value="expert_consensus">专家共识</a-select-option>
                        <a-select-option value="detection_report">检测报告</a-select-option>
                        <a-select-option value="csco">CSCO</a-select-option>
                        <a-select-option value="nccn">NCCN</a-select-option>
                        <a-select-option value="other">其他</a-select-option>
                    </a-select>
                </a-col>
                <!-- <a-col :span="4">
                    <a-select v-model:value="parsingStatusFilter" placeholder="解析状态" style="width: 100%"
                        @change="handleFilter" allow-clear>
                        <a-select-option value="pending">待解析</a-select-option>
                        <a-select-option value="processing">解析中</a-select-option>
                        <a-select-option value="completed">已完成</a-select-option>
                        <a-select-option value="failed">解析失败</a-select-option>
                    </a-select>
                </a-col> -->
                <a-col :span="6">
                    <a-range-picker v-model:value="dateRange" style="width: 100%" @change="handleFilter" />
                </a-col>
                <a-col :span="6" style="text-align: right">
                    <a-button @click="fetchDocuments" style="margin-right: 16px;">
                        <template #icon><reload-outlined /></template>
                        刷新列表
                    </a-button>
                    <a-button type="primary" @click="showUploadModal">
                        <template #icon><upload-outlined /></template>
                        上传文档
                    </a-button>
                </a-col>
            </a-row>
        </a-card>

        <!-- 数据表格 -->
        <a-card>
            <a-table :columns="columns" :data-source="filteredData" :loading="loading"
                :pagination="{ pageSize: 10, showSizeChanger: true, showTotal: (total: number) => `共 ${total} 条` }"
                row-key="id" :scroll="{ x: 1300 }">
                <template #bodyCell="{ column, record }">
                    <!-- 文档类型列 -->
                    <template v-if="column.dataIndex === 'document_type'">
                        <a-tag color="blue">{{ record.document_type }}</a-tag>
                    </template>

                    <!-- 知识库类型列 -->
                    <template v-if="column.dataIndex === 'knowledge_base_category'">
                        <a-tag :color="getCategoryColor(record.knowledge_base_category)">
                            {{ getCategoryText(record.knowledge_base_category) }}
                        </a-tag>
                    </template>

                    <!-- 解析状态列 -->
                    <template v-if="column.dataIndex === 'parsing_status'">
                        <a-tag :color="getParsingStatusColor(record.parsing_status)">
                            {{ getParsingStatusText(record.parsing_status) }}
                        </a-tag>
                    </template>

                    <!-- 操作列 -->
                    <template v-if="column.dataIndex === 'operation'">
                        <a-space>
                            <a-button type="link" @click="handleView(record)">查看</a-button>
                            <a-button type="link"
                                v-if="record.parsing_status !== 'completed' && record.parsing_status !== 'processing'"
                                @click="handleParse(record)">
                                解析
                            </a-button>
                            <a-popconfirm title="确定要删除此文档吗?" ok-text="确定" cancel-text="取消"
                                @confirm="handleDelete(record)">
                                <a-button type="link" danger>删除</a-button>
                            </a-popconfirm>
                        </a-space>
                    </template>
                </template>
            </a-table>
        </a-card>

        <!-- 查看详情模态框 -->
        <a-modal v-model:visible="viewModalVisible" title="文档详情" :footer="null" width="800px">
            <a-descriptions bordered :column="2">
                <a-descriptions-item label="文档名称">
                    {{ currentRecord.file_name }}
                </a-descriptions-item>
                <a-descriptions-item label="文档类型">
                    <a-tag color="blue">{{ currentRecord.document_type }}</a-tag>
                </a-descriptions-item>
                <a-descriptions-item label="知识库类型">
                    <a-tag :color="getCategoryColor(currentRecord.knowledge_base_category)">
                        {{ getCategoryText(currentRecord.knowledge_base_category) }}
                    </a-tag>
                </a-descriptions-item>
                <a-descriptions-item label="页数">
                    {{ currentRecord.page_count || '未知' }}
                </a-descriptions-item>
                <a-descriptions-item label="解析状态">
                    <a-tag :color="getParsingStatusColor(currentRecord.parsing_status)">
                        {{ getParsingStatusText(currentRecord.parsing_status) }}
                    </a-tag>
                </a-descriptions-item>
                <a-descriptions-item label="总结状态">
                    <a-tag :color="getSummaryStatusColor(currentRecord.summary_status)">
                        {{ getSummaryStatusText(currentRecord.summary_status) }}
                    </a-tag>
                </a-descriptions-item>
                <a-descriptions-item label="创建时间">
                    {{ formatDate(currentRecord.created_at) }}
                </a-descriptions-item>
                <a-descriptions-item label="更新时间">
                    {{ formatDate(currentRecord.updated_at) }}
                </a-descriptions-item>
                <a-descriptions-item label="文档链接" :span="2">
                    <a :href="currentRecord.file_url" target="_blank">查看文档</a>
                </a-descriptions-item>
                <a-descriptions-item label="封面图片" :span="2" v-if="currentRecord.cover_image_url">
                    <img :src="currentRecord.cover_image_url" alt="封面图片" style="max-width: 100%; max-height: 200px;" />
                </a-descriptions-item>
                <a-descriptions-item label="解析错误信息" :span="2" v-if="currentRecord.parsing_error">
                    <a-alert type="error" :message="currentRecord.parsing_error" />
                </a-descriptions-item>
            </a-descriptions>
        </a-modal>

        <!-- 上传文档模态框 -->
        <a-modal v-model:visible="uploadModalVisible" title="上传知识库文档" @ok="handleUploadConfirm"
            :confirm-loading="uploadLoading" :width="800" class="upload-modal" @cancel="handleUploadCancel">
            <a-form :model="uploadForm" :rules="uploadRules" ref="uploadFormRef" layout="vertical">
                <a-form-item label="知识库类型" name="knowledge_base_category" class="upload-form-item">
                    <a-select v-model:value="uploadForm.knowledge_base_category" size="large" style="width: 100%">
                        <a-select-option value="expert_consensus">专家共识</a-select-option>
                        <a-select-option value="detection_report">检测报告</a-select-option>
                        <a-select-option value="csco">CSCO</a-select-option>
                        <a-select-option value="nccn">NCCN</a-select-option>
                        <a-select-option value="other">其他</a-select-option>
                    </a-select>
                </a-form-item>
                <a-form-item label="文档文件" name="files" class="upload-form-item">
                    <div class="custom-upload-area" @dragover.prevent @drop.prevent="handleDrop"
                        @click="triggerFileInput">
                        <input type="file" ref="fileInput" multiple accept=".pdf,.doc,.docx,.txt" style="display: none"
                            @change="handleFileSelect">
                        <p class="upload-icon">
                            <inbox-outlined style="font-size: 48px; color: #40a9ff" />
                        </p>
                        <p class="upload-text">
                            点击或拖拽文件到此区域上传
                        </p>
                        <p class="upload-hint">
                            支持单个或批量上传，仅支持 PDF、Word、TXT 格式文件
                        </p>
                    </div>
                    <!-- 文件列表 -->
                    <div v-if="fileList.length > 0" class="file-list">
                        <div v-for="(file, index) in fileList" :key="index" class="file-item">
                            <file-outlined style="margin-right: 8px" />
                            <span class="file-name">{{ file.name }}</span>
                            <close-outlined class="remove-icon" @click="handleRemove(index)" />
                        </div>
                    </div>
                </a-form-item>
            </a-form>
        </a-modal>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue';
import { message } from 'ant-design-vue';
import {
    UploadOutlined,
    InboxOutlined,
    FileOutlined,
    CloseOutlined,
    CheckCircleOutlined,
    ClockCircleOutlined,
    CloseCircleOutlined,
    SyncOutlined,
} from '@ant-design/icons-vue';
import type { UploadRequestOption } from 'ant-design-vue/es/vc-upload/interface';
import {
    getKnowledgeBaseDocuments,
    batchUploadKnowledgeBaseDocuments,
    parseKnowledgeBaseDocument,
    deleteKnowledgeBaseDocument,
    OriginalDocument
} from '@/api/knowledge';
import dayjs from 'dayjs';
import api from '@/api';
import { useRouter } from 'vue-router';

// 表格列定义
const columns = [
    {
        title: '文档名称',
        dataIndex: 'file_name',
        key: 'file_name',
        width: 200,
        sorter: (a: OriginalDocument, b: OriginalDocument) => (a.file_name || '').localeCompare(b.file_name || '')
    },
    {
        title: '知识库类型',
        dataIndex: 'knowledge_base_category',
        key: 'knowledge_base_category',
        width: 120,
        customRender: ({ text }: { text: string }) => {
            const categoryMap: Record<string, string> = {
                'expert_consensus': '专家共识',
                'detection_report': '检测报告',
                'csco': 'CSCO',
                'nccn': 'NCCN',
                'other': '其他'
            };
            return categoryMap[text] || text;
        }
    },
    {
        title: '页数',
        dataIndex: 'page_count',
        key: 'page_count',
        width: 80,
        sorter: (a: OriginalDocument, b: OriginalDocument) => (a.page_count || 0) - (b.page_count || 0),
    },
    {
        title: '解析状态',
        dataIndex: 'parsing_status',
        key: 'parsing_status',
        width: 120,
        filters: [
            { text: '待解析', value: 'pending' },
            { text: '解析中', value: 'processing' },
            { text: '已完成', value: 'completed' },
            { text: '解析失败', value: 'failed' }
        ],
        onFilter: (value: string, record: OriginalDocument) => record.parsing_status === value,
    },
    {
        title: '创建时间',
        dataIndex: 'created_at',
        key: 'created_at',
        width: 150,
        customRender: ({ text }: { text: string }) => formatDate(text),
        sorter: (a: OriginalDocument, b: OriginalDocument) => new Date(a.created_at).getTime() - new Date(b.created_at).getTime(),
    },
    {
        title: '操作',
        dataIndex: 'operation',
        fixed: 'right',
        width: 200,
    }
];

// 状态变量
const loading = ref(false);
const searchKeyword = ref('');
const categoryFilter = ref(null);
const dateRange = ref<[dayjs.Dayjs, dayjs.Dayjs] | null>(null);
const viewModalVisible = ref(false);
const uploadModalVisible = ref(false);
const uploadLoading = ref(false);
const currentRecord = ref<OriginalDocument>({} as OriginalDocument);
const documentList = ref<OriginalDocument[]>([]);
const uploadFormRef = ref();
const fileList = ref<any[]>([]);
const router = useRouter();

// 上传表单
const uploadForm = reactive({
    knowledge_base_category: 'expert_consensus',
});

// 上传表单校验规则
const uploadRules = {
    knowledge_base_category: [{ required: true, message: '请选择知识库类型', trigger: 'change' }],
};

// 过滤后的数据
const filteredData = computed(() => {
    let result = [...documentList.value];

    // 关键词搜索
    if (searchKeyword.value) {
        const keyword = searchKeyword.value.toLowerCase();
        result = result.filter(item =>
            (item.file_name || '').toLowerCase().includes(keyword)
        );
    }

    // 类别筛选
    if (categoryFilter.value) {
        result = result.filter(item => item.knowledge_base_category === categoryFilter.value);
    }


    // 日期范围筛选
    if (dateRange.value && dateRange.value.length === 2) {
        const startDate = dateRange.value[0]?.format?.('YYYY-MM-DD') || '';
        const endDate = dateRange.value[1]?.format?.('YYYY-MM-DD') || '';
        if (startDate && endDate) {
            result = result.filter(item => {
                const itemDate = item.created_at.split('T')[0];
                return itemDate >= startDate && itemDate <= endDate;
            });
        }
    }

    return result;
});

// 根据知识库类型获取标签颜色
const getCategoryColor = (category: string) => {
    switch (category) {
        case 'expert_consensus': return 'red';
        case 'detection_report': return 'green';
        case 'csco': return 'blue';
        case 'nccn': return 'purple';
        case 'other': return 'orange';
        default: return 'default';
    }
};

// 获取知识库类型显示文本
const getCategoryText = (category: string) => {
    const categoryMap: Record<string, string> = {
        'expert_consensus': '专家共识',
        'detection_report': '检测报告',
        'csco': 'CSCO',
        'nccn': 'NCCN',
        'other': '其他'
    };
    return categoryMap[category] || category;
};

// 根据解析状态获取标签颜色
const getParsingStatusColor = (status: string) => {
    switch (status) {
        case 'pending': return 'default';
        case 'processing': return 'processing';
        case 'completed': return 'success';
        case 'failed': return 'error';
        default: return 'default';
    }
};

// 获取解析状态文本
const getParsingStatusText = (status: string) => {
    switch (status) {
        case 'pending': return '待解析';
        case 'processing': return '解析中';
        case 'completed': return '已完成';
        case 'failed': return '解析失败';
        default: return status;
    }
};

// 根据总结状态获取标签颜色
const getSummaryStatusColor = (status: string) => {
    switch (status) {
        case 'pending': return 'default';
        case 'processing': return 'processing';
        case 'completed': return 'success';
        case 'failed': return 'error';
        default: return 'default';
    }
};

// 获取总结状态文本
const getSummaryStatusText = (status: string) => {
    switch (status) {
        case 'pending': return '待总结';
        case 'processing': return '总结中';
        case 'completed': return '已完成';
        case 'failed': return '总结失败';
        default: return status;
    }
};

// 格式化日期
const formatDate = (date: string) => {
    if (!date) return '';
    return dayjs(date).format('YYYY-MM-DD HH:mm');
};

// 处理搜索
const handleSearch = (value: string) => {
    searchKeyword.value = value;
    fetchDocuments();
};

// 处理筛选
const handleFilter = (value: string) => {
    // 这里需要根据实际需求实现
    // 目前只处理了类别筛选和解析状态筛选
    // 如果需要处理更多筛选条件，可以在这里添加
    // if (value === '基因检测' || value === '病理检测' || value === '影像检测' || value === '生化检测' || value === '其他') {
    //     categoryFilter.value = value;
    // } else if (value === 'pending' || value === 'processing' || value === 'completed' || value === 'failed') {
    //     parsingStatusFilter.value = value;
    // }
    fetchDocuments();
};

// 处理日期范围变化
const handleDateRangeChange = (dates: [dayjs.Dayjs, dayjs.Dayjs] | null) => {
    dateRange.value = dates;
    fetchDocuments();
};

// 查看文档详情
const handleView = (record: OriginalDocument) => {
    router.push(`/knowledge/documents/${record.id}`);
};

// 显示上传模态框
const showUploadModal = () => {
    uploadModalVisible.value = true;
};

// 文件输入引用
const fileInput = ref<HTMLInputElement | null>(null);

// 触发文件选择
const triggerFileInput = () => {
    fileInput.value?.click();
};

// 处理文件选择
const handleFileSelect = (event: Event) => {
    const input = event.target as HTMLInputElement;
    if (input.files) {
        const newFiles = Array.from(input.files);
        addFiles(newFiles);
        input.value = ''; // 清空input，允许重复选择相同文件
    }
};

// 处理拖放
const handleDrop = (event: DragEvent) => {
    const files = Array.from(event.dataTransfer?.files || []);
    addFiles(files);
};

// 添加文件
const addFiles = (files: File[]) => {
    for (const file of files) {
        // 检查文件大小
        const isLt100M = file.size / 1024 / 1024 < 100;
        if (!isLt100M) {
            message.error(`文件 ${file.name} 大小不能超过 100MB!`);
            continue;
        }

        // 检查文件类型
        const allowedTypes = ['.pdf', '.doc', '.docx', '.txt'];
        const fileType = file.name.substring(file.name.lastIndexOf('.')).toLowerCase();
        if (!allowedTypes.includes(fileType)) {
            message.error(`文件 ${file.name} 格式不支持，仅支持 PDF、Word、TXT 格式!`);
            continue;
        }

        // 添加到文件列表
        fileList.value.push(file);
    }
};

// 移除文件
const handleRemove = (index: number) => {
    fileList.value.splice(index, 1);
};

// 取消上传
const handleUploadCancel = () => {
    uploadModalVisible.value = false;
    fileList.value = [];
    uploadForm.knowledge_base_category = 'expert_consensus';
    if (uploadFormRef.value) {
        uploadFormRef.value.resetFields();
    }
};

// 确认上传
const handleUploadConfirm = () => {
    if (!fileList.value || fileList.value.length === 0) {
        message.error('请选择文件');
        return Promise.reject();
    }

    return uploadFormRef.value.validate().then(() => {
        uploadLoading.value = true;
        const files = fileList.value;

        return batchUploadKnowledgeBaseDocuments(files, uploadForm.knowledge_base_category)
            .then(response => {
                message.success(response.message || '文档上传成功');
                handleUploadCancel(); // 重置表单和关闭弹窗
                fetchDocuments();
            })
            .catch(error => {
                message.error('文档上传失败: ' + (error.message || '未知错误'));
                throw error;
            })
            .finally(() => {
                uploadLoading.value = false;
            });
    }).catch(() => {
        message.error('请选择知识库类型');
        return Promise.reject();
    });
};

// 解析文档
const handleParse = async (record: OriginalDocument) => {
    try {
        await parseKnowledgeBaseDocument(record.id);
        message.success('文档解析任务已提交');
        fetchDocuments();
    } catch (error) {
        message.error('文档解析任务提交失败');
    }
};

// 删除文档
const handleDelete = async (record: OriginalDocument) => {
    try {
        await deleteKnowledgeBaseDocument(record.id);
        message.success('文档删除成功');
        fetchDocuments();
    } catch (error) {
        message.error('文档删除失败');
    }
};

// 切换文档可见性
const handleVisibilityChange = async (record: OriginalDocument, checked: boolean) => {
    try {
        await api.patch(`/api/original-documents/${record.id}/`, {
            visible: checked
        });
        message.success(`文档${checked ? '已设为可见' : '已设为不可见'}`);
        fetchDocuments();
    } catch (error) {
        message.error('文档可见性更新失败');
    }
};

// 获取文档列表
const fetchDocuments = () => {
    loading.value = true;

    getKnowledgeBaseDocuments()
        .then(data => {
            documentList.value = data;
        })
        .catch(error => {
            message.error('获取文档列表失败: ' + (error.message || '未知错误'));
        })
        .finally(() => {
            loading.value = false;
        });
};

// 自定义上传请求
const customRequest = (options: UploadRequestOption) => {
    if (options.onSuccess) {
        options.onSuccess({} as any);
    }
};

// 生命周期钩子
onMounted(() => {
    fetchDocuments();
});
</script>

<style scoped>
.knowledge-documents-container {
    padding: 0;
    width: 100%;
}

.upload-modal {
    :deep(.ant-modal-content) {
        padding: 24px;
    }

    :deep(.ant-modal-header) {
        margin-bottom: 24px;
    }

    :deep(.ant-modal-title) {
        font-size: 20px;
        font-weight: 500;
    }

    :deep(.ant-form-item-label) {
        font-size: 16px;
        font-weight: 500;
    }

    .upload-form-item {
        margin-bottom: 24px;
    }

    :deep(.ant-upload-drag) {
        padding: 32px;
        border-radius: 8px;
    }
}

.custom-upload-area {
    width: 100%;
    padding: 32px;
    background: #fafafa;
    border: 1px dashed #d9d9d9;
    border-radius: 8px;
    cursor: pointer;
    text-align: center;
    transition: border-color 0.3s;
}

.custom-upload-area:hover {
    border-color: #40a9ff;
}

.upload-icon {
    margin-bottom: 16px;
}

.upload-text {
    font-size: 16px;
    margin: 16px 0;
    color: rgba(0, 0, 0, 0.85);
}

.upload-hint {
    color: rgba(0, 0, 0, 0.45);
}

.file-list {
    margin-top: 16px;
}

.file-item {
    display: flex;
    align-items: center;
    padding: 8px;
    margin-bottom: 8px;
    background: #fafafa;
    border-radius: 4px;
}

.file-name {
    flex: 1;
    margin-right: 8px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.remove-icon {
    color: #999;
    cursor: pointer;
    transition: color 0.3s;
}

.remove-icon:hover {
    color: #ff4d4f;
}
</style>